package com.empresa.piloto01.pessoa.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.empresa.piloto01.pessoa.entity.Pessoa;
import com.empresa.piloto01.pessoa.service.PessoaService;

@Controller
public class PessoaController {

	@Autowired
	private PessoaService service;

	// @InitBinder
	// private void dateBinder(WebDataBinder binder) {
	// // The date format to parse or output your dates
	// SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	// // Create a new CustomDateEditor
	// CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
	// // Register it as custom editor for the Date type
	// binder.registerCustomEditor(Date.class, editor);
	// }

	@RequestMapping(value = "/pessoa/read.action", method = RequestMethod.GET)
	public @ResponseBody Map<String, ? extends Object> findAll(int page,
			int start, int limit) throws Exception {

		Map<String, Object> response = new HashMap<String, Object>(3);

		List<Pessoa> data = service.findAll(limit, start);

		response.put("total", service.count());
		response.put("data", data);
		response.put("success", true);

		return response;

	}

	@RequestMapping(value = "/pessoa/delete.action", method = RequestMethod.POST)
	public @ResponseBody Map<String, ? extends Object> delete(Long id)
			throws Exception {

		Map<String, Object> response = new HashMap<String, Object>(3);
		service.delete(id);
		response.put("success", true);
		response.put("message", "Registro Apagado!");

		return response;

	}

	@RequestMapping(value = "/pessoa/update.action", method = RequestMethod.POST)
	public @ResponseBody Map<String, ? extends Object> update(Pessoa e)
			throws Exception {
		Map<String, Object> response = new HashMap<String, Object>(3);
		service.update(e);
		response.put("success", true);
		response.put("message", "Registro Salvo!");

		return response;
	}

	@RequestMapping(value = "/pessoa/create.action", method = RequestMethod.POST)
	public @ResponseBody Map<String, ? extends Object> create(Pessoa e)
			throws Exception {
		Map<String, Object> response = new HashMap<String, Object>(3);
		e = service.save(e);
		response.put("success", true);
		response.put("message", "Registro Salvo!");

		return response;
	}

}
